<?php
/**
 *+------------------
 * Lflow
 *+------------------
 * Copyright (c) 2023~2030 gitee.com/liu_guan_qing All rights reserved.本版权不可删除，侵权必究
 *+------------------
 * Author: Mr.April(405784684@qq.com)
 *+------------------
 */

namespace lflow\core\services;

use lflow\core\BaseServices;
use lflow\dao\DesignerDao;
use lflow\exceptions\WorkFlowException;

class DesignerServices extends BaseServices
{

    /**
     * @param \lflow\dao\DesignerDao $dao
     */
    public function __construct(DesignerDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 保存资源
     *
     * @param array $data
     *
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save(array $data): mixed
    {
        if ($this->dao->getOne(['model_key' => $data['model_key']])) {
            throw new WorkFlowException('该模型编码已存在');
        }
        $res = $this->dao->save($data);
        if (!$res) throw new WorkFlowException('保存失败');
        return $res;
    }

    /**
     * 保存修改资源
     *
     * @param string $id
     * @param array  $data
     *
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function update(string $id, array $data): mixed
    {
        $result = $this->dao->getOne(['id' => $id]);
        if ($result && $result['id'] != $id) {
            throw new WorkFlowException('该分类已存在');
        }
        return $this->dao->update($id, $data);
    }

    /**
     * 删除分类
     *
     * @param string $id
     *
     * @return mixed
     */
    public function del(string $id): mixed
    {
        $count = $this->count(['id' => $id]);
        if ($count) {
            return $this->dao->destroy($id);
        }
    }

    /**
     * 分组列表
     *
     * @param array $where
     *
     * @return array
     * @throws \ReflectionException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function select(array $where): array
    {
        [$page, $limit] = $this->getPageValue();
        $list  = $this->dao->selectList($where, '*', $page, $limit, 'model_name', [], true);
        $count = $this->dao->count($where);
        return compact('list', 'count');
    }

    /**
     * 查询指定数据
     *
     * @param string $id
     *
     * @return array|\think\Model|null
     */
    public function find(string $id): array|\think\Model|null
    {
        return $this->get($id, ['*']);
    }

}
